
package org.jivesoftware.util;

import java.io.InputStream;

/**
 * 工具类
 * @author zhujin
 *
 */
public class ClassUtils {

    private static ClassUtils instance = new ClassUtils();

    public static Class forName(String className) throws ClassNotFoundException {
        return instance.loadClass(className);
    }

    public static InputStream getResourceAsStream(String name) {
        return instance.loadResource(name);
    }

    private ClassUtils() {}

    /**
     * 加载类
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    public Class loadClass(String className) throws ClassNotFoundException {
        Class theClass = null;
        try {
            theClass = Class.forName(className);
        }
        catch (ClassNotFoundException e1) {
            try {
                theClass = Thread.currentThread().getContextClassLoader().loadClass(className);
            }
            catch (ClassNotFoundException e2) {
                theClass = getClass().getClassLoader().loadClass(className);
            }
        }
        return theClass;
    }

    /**
     * 加载资源
     * @param name
     * @return
     */
    private InputStream loadResource(String name) {
        InputStream in = getClass().getResourceAsStream(name);
        if (in == null) {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
            if (in == null) {
                in = getClass().getClassLoader().getResourceAsStream(name);
            }
        }
        return in;
    }
}
